import time

from django import forms
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models


class CommonBody(models.Model):
    uuid = models.CharField(max_length=200)
    time = models.CharField(max_length=200)


class CustomMgr(BaseUserManager):
    def create_user(self, username, password=None, is_lawyer=False):
        # print("create_user:" + str(username))
        if not username:
            raise ValueError('User must have an username')

        user = self.model(uid=username, username=username)
        user.set_password(password)
        user.is_lawyer = is_lawyer
        user.save(using=self._db)
        return user


def create_superuser(self, username, password=None):
    """
    Creates and saves a superuser with the given email, date of
    birth and password.
    """
    user = self.create_user(username, password=password)
    user.is_admin = True
    user.is_staff = True
    user.is_superuser = True
    user.save(using=self._db)
    return user


class User(AbstractBaseUser, PermissionsMixin):
    uid = models.CharField(verbose_name="id", max_length=100, primary_key=True)
    username = models.CharField(verbose_name="用户名", max_length=100, unique=True)
    avatar = models.CharField(verbose_name="头像", max_length=2048, default="", null=True, blank=True)
    nickname = models.CharField(verbose_name="昵称", max_length=200, default="", null=True, blank=True)
    phone = models.CharField(verbose_name="手机号", max_length=200, default="", blank=True)
    is_lawyer = models.BooleanField(verbose_name="是否是律师", default=False)
    introduce = models.CharField(verbose_name="简介", max_length=200, default="", null=True, blank=True)
    address = models.CharField(verbose_name="地址", max_length=200, default="", null=True, blank=True)
    gender = models.IntegerField(verbose_name="性别", default=0)
    specialty = models.CharField(verbose_name="擅长领域", max_length=200, default="", null=True, blank=True)
    seniority = models.IntegerField(verbose_name="工龄", default=1, null=True, blank=True)
    company = models.CharField(verbose_name="公司", max_length=200, default="none", null=True, blank=True)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'username'
    objects = CustomMgr()

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户管理'
        db_table = "db_users"

    def clean(self):
        super().clean()

    def __str__(self):
        return "{}(is_lawyer:{})".format(self.nickname, self.is_lawyer)


class UploadImage(models.Model):
    name = models.CharField(verbose_name="图片名", max_length=50)
    image = models.FileField(upload_to='images/', verbose_name='图片')
    # 创建时间
    time = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '图片'
        verbose_name_plural = verbose_name


# 使用ModelForm方式上传图片
class ImageForm(forms.ModelForm):
    class Meta:
        model = UploadImage
        fields = ['image']

    # 校验图片合法性、同时修改名字
    def clean_image(self):
        file = self.cleaned_data['image']
        ext = file.name.split(".")[-1].lower()
        # if ext != "png":
        #     raise forms.ValidationError("仅允许上传png文件")
        file.name = time.strftime("image" + '-%Y%m%d%H%M%S', time.localtime()) + "." + ext
        return file

    def get_image_url(self):
        file = self.cleaned_data['image']
        return "http://localhost:5000/media/images/" + file.name
        # images = UploadImage.objects.all()
        # # images/image-20231114103204.png --- image-20231114103204.png
        # for i in images:
        #     # 这里暂时匹配一下，后续找其他匹配方法
        #     if file.name in i.image.name:
        #         return i.image.path
        # return "image not exist"
